/**
 * Copyright (c) 2017-2018,Retire 吴益峰 (372310383@qq.com).
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package io.jplus.core.web.base;

import com.google.common.base.CaseFormat;
import com.jfinal.core.NotAction;
import com.jfinal.json.FastJson;
import com.jfinal.kit.JsonKit;
import com.jfinal.kit.LogKit;
import com.jfinal.kit.Ret;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.activerecord.Page;
import io.jboot.Jboot;
import io.jboot.web.controller.JbootController;
import io.jplus.JplusConsts;
import io.jplus.common.Query;
import io.jplus.utils.PageUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class BaseController extends JbootController {

    public static final String BASE_VIEW_PATH = JplusConsts.BASE_VIEW_PATH;


    @NotAction
    protected int getPageNumber() {
        int page = getParaToInt("page", 1);
        if (page < 1) {
            page = 1;
        }
        return page;
    }

    @NotAction
    protected int getPageSize() {
        int size = getParaToInt("limit", 10);
        if (size < 1) {
            size = 1;
        }
        return size;
    }


    public String getUserId() {
       return getAttr(JplusConsts.JPLUS_USER_ID);
    }
    /**
     * 将前端传递过来的Json转换成对应的Model对象
     *
     * @param t   Model对象类
     * @param <T> 返回对应的Model对象
     * @return
     */
    @NotAction
    protected <T extends Model> T jsonToModel(Class<T> t) {
        String jsonString = getRawData();
        T model = null;
        if (StrKit.notBlank(jsonString)) {
            try {
                Map<String, Object> map = FastJson.getJson().parse(jsonString, Map.class);
                Map<String, Object> modelMap = new HashMap<>();
                for (String key : map.keySet()) {
                    String tmpKey = CaseFormat.LOWER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, key);
                    modelMap.put(tmpKey, map.get(key));
                }
                model = t.newInstance();
                model.put(modelMap);
            } catch (InstantiationException e) {
                LogKit.error(e.getMessage(),e.getCause());
            } catch (IllegalAccessException e) {
                LogKit.error(e.getMessage(),e.getCause());
            }
        }
        return model;
    }


    /**
     * 将前端传递过来的Json转换成对应的map对象
     *
     * @return
     */
    @NotAction
    protected Map<String, Object> jsonToMap() {
        Map<String, Object> params = new HashMap<>();
        String jsonString = getRawData();
        if (StrKit.notBlank(jsonString)) {
            params = FastJson.getJson().parse(jsonString, Map.class);
        }
        return params;
    }

    @NotAction
    protected List<Object> jsonToList() {
        String jsonString = getRawData();
        List list = FastJson.getJson().parse(jsonString, List.class);
        return list;
    }

    @NotAction
    protected Query getQuery() {
        return new Query(getParaMap());
    }

    @NotAction
    protected void renderJsonForSuccess() {
        renderJsonForSuccess("操作成功！");
    }

    @NotAction
    protected void renderJsonForSuccess(String message) {
        renderJsonForSuccess(0, message);
    }

    @NotAction
    protected void renderJsonForSuccess(int code, String message) {
        renderJson(Ret.ok(JplusConsts.RET_CODE, code).set(JplusConsts.RET_MSG, message));
    }

    @NotAction
    protected void renderJsonForFail() {
        renderJsonForFail("操作失败！");
    }

    @NotAction
    protected void renderJsonForFail(String message) {
        renderJsonForFail(1, message);
    }

    @NotAction
    protected void renderJsonForFail(int code, String message) {
        renderJson(Ret.fail(JplusConsts.RET_CODE, code).set(JplusConsts.RET_MSG, message));
    }

    @NotAction
    protected void renderJsonPage(Page<?> page) {
        if (Jboot.isDevMode()) {
            System.out.println("--------------------------------------------------------------------------------");
            System.out.println(JsonKit.toJson(new PageUtils(page)));
            System.out.println("--------------------------------------------------------------------------------");
        }
        renderJson(Ret.ok(JplusConsts.RET_CODE, 0).set("page", new PageUtils(page)));
    }
}
